import os
import subprocess
from pathlib import Path
import time
import tempfile
import re  # 新增正则表达式模块

def check_pandoc_installed():
    try:
        subprocess.run(["pandoc", "--version"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except (subprocess.CalledProcessError, FileNotFoundError):
        return False

def convert_md_to_pdf(md_file, output_dir):
    start_time = time.time()
    pdf_file = os.path.join(output_dir, f"{Path(md_file).stem}.pdf")
    
    # 获取Markdown文件所在目录
    md_dir = os.path.dirname(os.path.abspath(md_file))
    
    # 构建图片目录路径
    images_dir = os.path.join(md_dir, 'images')
    
    # 创建临时Lua过滤器
    lua_code = '''function Image (img)
    img.attributes["src"] = img.src:gsub("^images/", "")
    return img
end'''

    # 创建临时文件并获取路径
    with tempfile.NamedTemporaryFile(mode='w', suffix='.lua', delete=False, encoding='utf-8') as temp_lua:
        temp_lua.write(lua_code)
        lua_filter = temp_lua.name
    
    # 检查图片目录是否存在
    if not os.path.exists(images_dir):
        print(f"警告：目录 {images_dir} 不存在，图片可能无法显示")
    
    try:
        result = subprocess.run([
            "pandoc", 
            md_file, 
            "-o", pdf_file,
            "--pdf-engine=xelatex",
            "--variable=mainfont=SimSun",
            "--variable=sansfont=SimHei",
            "--variable=monofont=FangSong",
            "--variable=classoption=table,a4paper",
            "--variable=documentclass=ctexart",
            "--variable=geometry:left=2.8cm,right=2.8cm,top=2.5cm,bottom=2.5cm",
            "--variable=fontsize=16pt",
            "--variable=linespread=1.3",
            "--variable=graphics=yes",
            "--resource-path", f".;{md_dir};{images_dir}",
            "--extract-media", output_dir,
            "--lua-filter", lua_filter
        ], 
            check=True, 
            capture_output=True, 
            text=True,
            encoding='utf-8',
            errors='ignore'
        )
        
        if result.returncode == 0:
            elapsed = time.time() - start_time
            print(f"成功转换: {md_file} -> {pdf_file}, 耗时: {elapsed:.2f}秒")
        else:
            elapsed = time.time() - start_time
            print(f"转换失败: {md_file}, 错误: {result.stderr}, 耗时: {elapsed:.2f}秒")
    except subprocess.CalledProcessError as e:
        elapsed = time.time() - start_time
        print(f"转换失败: {md_file}, 错误: {e.stderr}, 耗时: {elapsed:.2f}秒")
    except Exception as e:
        elapsed = time.time() - start_time
        print(f"转换过程中发生未知错误: {md_file}, 错误: {str(e)}, 耗时: {elapsed:.2f}秒")
    finally:
        # 清理临时文件
        if os.path.exists(lua_filter):
            os.remove(lua_filter)
    
    return time.time() - start_time

def process_directory(root_dir):
    if not check_pandoc_installed():
        print("错误: pandoc未安装，请先安装pandoc")
        return

    total_start = time.time()
    total_files = 0
    total_time = 0

    for entry in os.listdir(root_dir):
        entry_path = os.path.join(root_dir, entry)
        if os.path.isdir(entry_path):
            dir_start = time.time()
            dir_files = 0
            dir_time = 0
            
            for file in os.listdir(entry_path):
                # 修改文件过滤条件：仅处理符合"md优化-数字.md"格式的文件
                if re.match(r'^.*md优化-\d+\.md$', file):
                    md_file = os.path.join(entry_path, file)
                    elapsed = convert_md_to_pdf(md_file, entry_path)
                    dir_time += elapsed
                    dir_files += 1
                    total_time += elapsed
                    total_files += 1
            
            dir_elapsed = time.time() - dir_start
            print(f"目录 {entry} 处理完成: 共处理 {dir_files} 个文件, 耗时: {dir_elapsed:.2f}秒, 平均每个文件: {dir_time/dir_files:.2f}秒" if dir_files > 0 else f"目录 {entry} 无文件处理")
    
    total_elapsed = time.time() - total_start
    print(f"\n所有文件处理完成: 共处理 {total_files} 个文件, 总耗时: {total_elapsed:.2f}秒, 平均每个文件: {total_time/total_files:.2f}秒" if total_files > 0 else "无文件处理")

if __name__ == "__main__":
    current_dir = os.path.dirname(os.path.abspath(__file__))
    process_directory(current_dir)
    input("按任意键退出...")